import torch
import  torchvision
from torch import nn
from torch.utils.data import DataLoader
from model import *

# vgg16_false = torchvision.models.vgg16(pretrained=False)
# vgg16_true = torchvision.models.vgg16(pretrained=True)
#
# train_data=torchvision.datasets.CIFAR10("./dataset",train=True,transform=torchvision.transforms.ToTensor(),download=True)
#
# vgg16_true.classifier.add_module("add_linear",nn.Linear(1000,10))
# print(vgg16_true)
#
#
# vgg16_false.classifier[6]=nn.Linear(4096,10)
# print(vgg16_false)

# vgg16_false = torchvision.models.vgg16(pretrained=False)
# # 保存方式1,模型结构+参数
# torch.save(vgg16_false,"vgg16_method1.pth")
# # model=torch.load("vgg16_method1.pth")
#
# # 保存方式2
# torch.save(vgg16_false.state_dict(),"vgg16_method2.pth")
# # 模型参数（官方推荐） vgg16=torchvision.models.vgg16(pretained=False)
# #                  vgg16.load_state_dict(torch.load("vgg16_method2.pth)))
# #                  model=torch.load("vgg16_method2.pth")
#

train_data=torchvision.datasets.CIFAR10("./dataset",train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_data=torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)

train_data_size = len(train_data)
test_data_size = len(test_data)
print(f"训练数据集的长度为{train_data_size}")
print(f"测试数据集的长度为{test_data_size}")

train_dataloader=DataLoader(train_data,batch_size=64)
test_dataloader=DataLoader(test_data,batch_size=64)

jjw=JJw()

# 损失函数
loss_fun = nn.CrossEntropyLoss()

# 优化器
learn_rate=0.01
optimizer=torch.optim.SGD(params=jjw.parameters(),lr=learn_rate)

# 设置训练网络的一些参数
total_train_step=0 # 记录训练的次数
total_test_step=0  # 记录测试的次数
epoch=10 # 训练的轮数

for i in range(epoch):
    print(f"第{i+1}轮训练开始")

    # 训练步骤开始
    for data in train_dataloader:
        imgs,targets=data
        outputs=jjw(imgs)
        loss=loss_fun(outputs,targets)
        # 优化器优化模型 参数
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        # 记录训练次数
        total_train_step+=1
        print(f"训练次数={total_train_step},Loss={loss}")
        